package com.feitubc.tools.fileimport.service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.feitubc.tools.fileimport.StrategyContext;
import com.feitubc.tools.fileimport.builder.FileStrategyBuilders;
import com.feitubc.tools.fileimport.domain.FileStrategySetting;
import com.feitubc.tools.fileimport.domain.ImportFileResultEnum;
import com.feitubc.tools.fileimport.domain.ImportLogObject;
import com.feitubc.tools.fileimport.util.DateHelper;

/**
 * 文件上传提供通用服务
 * 
 * @author zhc
 */
@Service("baseUploadFileService")
public class BaseUploadFileService implements IBaseUploadFile {

    protected final Log logger = LogFactory.getLog(this.getClass());
    
    private FileStrategyBuilders fileStrategyBuilders;
    
    @Override
    public List<FileStrategySetting> getFileStrategySettingsByGropyType(String groupType) {
    	if (fileStrategyBuilders != null && StringUtils.isNotBlank(groupType)) {
    		return fileStrategyBuilders.getAll(groupType);
    	}
    	return null;
    }
    
    @Override
    public FileStrategySetting getFileStrategyByTypeKey(String groupType, String strategyServiceType){
    	if (fileStrategyBuilders != null) {
    		return this.fileStrategyBuilders.get(groupType, strategyServiceType);
    	}
    	return null;
    }
    
    @Override
    public FileStrategySetting getFileStrategy(FileStrategySetting fileStrategySetting) {
    	if (fileStrategyBuilders != null && fileStrategyBuilders != null) {
    		return this.getFileStrategyByTypeKey(fileStrategySetting.getGroupType(), fileStrategySetting.getStrategyServiceType());
    	}
    	return null;
    }

	@Override
	public boolean doUpload(StrategyContext strategyContext) {
		//结果列表
		boolean result = false;
		try {
			
			boolean isContinue = true;
			if (strategyContext == null) {
				// 验证上下文信息
				isContinue = false;
			} else if (strategyContext.getInputStream() == null) {
				// 验证导入为空
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.FILE_PARAM_ERROR);
				isContinue = false;
			} else if (StringUtils.isBlank(strategyContext.getFilename())) {
				// 验证导入文件名信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_FOUND_FILENAME_ERROR);
				isContinue = false;
			} else if (strategyContext == null 
					|| strategyContext.getFileStrategySetting() == null 
					|| StringUtils.isBlank(strategyContext.getFileStrategySetting().getGroupType())
					|| StringUtils.isBlank(strategyContext.getFileStrategySetting().getStrategyServiceType())) {
				// 验证操作类别信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_FOUND_TYPE_ERROR);
				isContinue = false;
			}
			FileStrategySetting fileStrategySetting = this.getFileStrategy(strategyContext.getFileStrategySetting());
			if (fileStrategySetting == null) {
				// 验证操作类别信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_FOUND_TYPE_ERROR);
				isContinue = false;
			} else if (fileStrategySetting.isValidFilename() && (StringUtils.isBlank(fileStrategySetting.getStrategyName())
								|| !strategyContext.getFilename().startsWith(fileStrategySetting.getStrategyName()))) {
				// 导入文件名不合规范
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_STANDARD_FILENAME_ERROR, 
						String.format("导入文件名称不合规范，导入【%s】类别必须以【%s】开头！", fileStrategySetting.getStrategyName(), fileStrategySetting.getStrategyName()));
				isContinue = false;
			} else if (fileStrategySetting.isValidLoginUser() && (strategyContext.getCreateUserId() == null || strategyContext.getCreateUserId() <= 0)) {
				// 验证登录人信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NO_PERMISSION_ERROR);
				isContinue = false;
			}
			
			if (isContinue) {
				strategyContext.setFileStrategySetting(fileStrategySetting);
				strategyContext.setBatch(fileStrategySetting.getGroupType() + "_" + fileStrategySetting.getStrategyServiceType() + "_" + DateHelper.getCurrentDateStr("yyyyMMddHHmmssSSS"));
				
				result = strategyContext.doExecute();

				List<ImportLogObject> dataList = strategyContext.getImportLogObjects();

				if (dataList != null && dataList.size() > 0) {
					Collections.sort(dataList, new Comparator<ImportLogObject>() {

						@Override
						public int compare(ImportLogObject o1, ImportLogObject o2) {
							if (o1 != null && o2 != null && o1.getStatus() != null && o2.getStatus() != null) {
								return o1.getExcelNo() - o2.getExcelNo();
							}
							return 0;
						}
					});
					Collections.sort(dataList, new Comparator<ImportLogObject>() {

						@Override
						public int compare(ImportLogObject o1, ImportLogObject o2) {
							if (o1 != null && o2 != null && o1.getStatus() != null && o2.getStatus() != null) {
								return o1.getStatus() - o2.getStatus();
							}
							return 0;
						}
					});
				}				
			}
			
		} catch (Exception e) {
			logger.error("BaseUploadFileService#doUpload read readFile Exception :", e);
		}
		return result;
	}

	public void setFileStrategyBuilders(FileStrategyBuilders fileStrategyBuilders) {
		this.fileStrategyBuilders = fileStrategyBuilders;
	}

}
